package com.otaku.admin.service;

import com.otaku.admin.dao.PermissionMapper;
import com.otaku.admin.dao.UserMapper;
import com.otaku.admin.dao.entity.Permission;
import com.otaku.admin.dao.entity.Role;
import com.otaku.admin.dao.entity.SelfUserDetails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author: zzx
 * @date: 2018/10/15 16:54
 * @description: 用户认证、权限
 */
@Component
public class SelfUserDetailsService implements UserDetailsService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SelfUserDetailsService.class);

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //通过username查询用户
        SelfUserDetails user = userMapper.findByUsername(username);
        if (user == null) {
            //仍需要细化处理
            throw new UsernameNotFoundException("该用户不存在");
        }
        LOGGER.info("用户{}验证通过", username);
        return user;
    }

    public void register(SelfUserDetails userDetails) {
        userMapper.insertUserDetail(userDetails);
    }

    public SelfUserDetails findByUserId(Integer userId){
        return userMapper.findUserById(userId);
    }
}
